<?php
declare (strict_types = 1);

namespace app\api\model;

use think\Model;
use think\facade\Cache;

class User extends Model
{
    // 设置表名
    protected $name = 'user';
    
    // 设置主键
    protected $pk = 'id';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 设置时间字段
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 类型转换
    protected $type = [
        'status'          => 'integer',
        'last_login_time' => 'integer',
        'create_time'     => 'integer',
        'update_time'     => 'integer',
    ];

    /**
     * 登录
     * @param string $username 用户名或手机号
     * @param string $password 密码
     * @return array
     * @throws \Exception
    
    public function login(string $username, string $password): array
    {
        // 查找用户(支持用户名或手机号登录)
        $user = $this->where([
            ['status', '=', 1],
            ['delete_time', '=', null]
        ])
        ->where(function ($query) use ($username) {
            $query->whereOr([
                ['username', '=', $username],
                ['phone', '=', $username]
            ]);
        })
        ->find();

        if (!$user) {
            throw new \Exception('账号不存在或已被禁用');
        }

        // 验证密码
        if (!password_verify($password, $user->password)) {
            throw new \Exception('密码错误');
        }

        // 生成token
        $token = md5(uniqid((string)mt_rand(), true));
        
        // 保存token到缓存
        Cache::set('user_token_' . $token, $user->id, 86400);

        // 更新登录信息
        $user->save([
            'last_login_time' => time(),
            'last_login_ip'   => request()->ip()
        ]);

        return [
            'token' => $token,
            'user_info' => [
                'id'       => $user->id,
                'username' => $user->username,
                'phone'    => $user->phone,
                'nickname' => $user->nickname,
                'avatar'   => $user->avatar
            ]
        ];
    }
 */
    /**
     * 注册
     * @param array $data
     * @return array
     * @throws \Exception
     */
    public function register(array $data): array
    {
        // 检查用户名是否存在
        if ($this->where('username', $data['username'])->whereNull('delete_time')->find()) {
            throw new \Exception('用户名已存在');
        }

        // 检查手机号是否存在
        if (!empty($data['phone']) && $this->where('phone', $data['phone'])->whereNull('delete_time')->find()) {
            throw new \Exception('手机号已存在');
        }

        // 创建用户
        $user = self::create([
            'username' => $data['username'],
            'phone'    => $data['phone'] ?? '',
            'password' => $data['password'],
            'nickname' => $data['nickname'] ?? $data['username'],
            'avatar'   => $data['avatar'] ?? '',
            'status'   => 1
        ]);

        // 生成token
        $token = md5(uniqid((string)mt_rand(), true));
        Cache::set('user_token_' . $token, $user->id, 86400);

        return [
            'token' => $token,
            'user_info' => [
                'id'       => $user->id,
                'username' => $user->username,
                'phone'    => $user->phone,
                'nickname' => $user->nickname,
                'avatar'   => $user->avatar
            ]
        ];
    }

    /**
     * 修改密码
     * @param int $userId
     * @param string $oldPassword
     * @param string $newPassword
     * @return bool
     * @throws \Exception
     */
    public function changePassword(int $userId, string $oldPassword, string $newPassword): bool
    {
        $user = $this->find($userId);
        if (!$user) {
            throw new \Exception('用户不存在');
        }

        if (!password_verify($oldPassword, $user->password)) {
            throw new \Exception('原密码错误');
        }

        return $user->save([
            'password' => password_hash($newPassword, PASSWORD_DEFAULT)
        ]);
    }

    /**
     * 重置密码
     * @param string $phone
     * @param string $newPassword
     * @return bool
     * @throws \Exception
     */
    public function resetPassword(string $phone, string $newPassword): bool
    {
        $user = $this->where('phone', $phone)->whereNull('delete_time')->find();
        if (!$user) {
            throw new \Exception('用户不存在');
        }

        return $user->save([
            'password' => password_hash($newPassword, PASSWORD_DEFAULT)
        ]);
    }

    /**
     * 更新用户信息
     * @param int $userId
     * @param array $data
     * @return bool
     */
    public function updateInfo(int $userId, array $data): bool
    {
        $allowFields = ['nickname', 'avatar', 'phone'];
        $updateData = array_intersect_key($data, array_flip($allowFields));
        
        return $this->where('id', $userId)->update($updateData);
    }

    /**
     * 密码加密
     * @param string $value
     * @return string
     */
    public function setPasswordAttr($value): string
    {
        return password_hash($value, PASSWORD_DEFAULT);
    }

    /**
     * 头像获取器
     * @param string|null $value
     * @return string
     */
    public function getAvatarAttr($value): string
    {
        if (empty($value)) {
            return '';
        }
        return strpos($value, 'http') === 0 ? $value : env('OSS_DOMAIN', '') . $value;
    }
}
